<?php
/**
 * PublicController.class.php - 后台公开访问
 * @package Controller
 * @subpackage null
 * @link http://www.xxx.com
 * @author xxx PHP DEV TEAM JiRY(390066398@qq.com)
 * @copyright 2016-10-28 9:40
 */
namespace Admin\Controller;
use Admin\Controller\BaseController;
class PublicController extends BaseController {
    /**
     * 初始化
     */
    public function _initialize() {
        parent::_initialize();
        
        // 无需签名认证列表
        $not_verify = ['public_verify'];
        
        if(!in_array(strtolower(CONTROLLER_NAME.'_'.ACTION_NAME), $not_verify)){
            // 数据签名认证
            if(!verify_sign(I('post.sign'), I('post.'))){
                $this->ajaxReturnError([
                    'msg'    => L('SIGN_ERROR')
                ]);
            }
        }
        
    }
    /**
     * 验证码
     */
    public function verify(){
        //验证码字体大小
        $fontSize       = trim(I('get.fontSize')) ? trim(I('get.fontSize')) : 16;
        //验证码位数
        $length         = trim(I('get.length')) ? trim(I('get.length')) : 4;
        //关闭验证码杂点
        $useNoise       = isset($_GET['useNoise']) ? (trim(I('get.useNoise')) == 0 ? false : true) : false;
        //验证码图片高度
        $height         = trim(I('get.height')) ? trim(I('get.height')) : 38;
        //验证码图片宽度
        $width          = trim(I('get.width')) ? trim(I('get.width')) : 110;
        
        $config = array(
            'fontSize'      => $fontSize,         
            'length'        => $length,          
            'useNoise'      => $useNoise,       
            'imageH'        => $height,             
            'imageW'        => $width,
            'fontttf'       => '5.ttf'
        );
        
        $Verify =new \Think\Verify( $config );
        $Verify->entry();
    }
    
    /**
     * 管理员登陆
     * @return json
     */
    public function login(){
    	// 请求类型
    	if(!IS_POST){
    		$auth_key = C('AUTH_CONFIG.AUTH_KEY');
            //检测是否的登录，如果已登录跳转首页
            if( session($auth_key) ){
            	$this->ajaxReturnSuccess([
            		'flag'	=> 'redirect',
            		'url'	=> 'Index/index'
            	]);
            }
            
            $result['flag']   = 'tips';
            $result['msg']    = L('REQUEST_TYPE_ERROR');
            $this->ajaxReturnError($result);
    	}
    	
    	// 接收参数
    	$account        = I('post.loginname', '', 'trim');
        $passwd         = I('post.password', '', 'trim');
        $verify         = I('post.code', '', 'trim');
        
        //数据验证
//	    $data = array(
//	        'admin_account'     => $account,
//	        'admin_pass'        => $passwd,
//	        'verify'            => $verify
//	    );
//      $validate_result = D('Admin' , 'Logic')->validateLoginData( $data );
//      if($validate_result !== true){
//          $error = explode('-', $validate_result);
//          $this->result['flag']   = $error[0];
//          $this->result['msg']    = $error[1];
//          $this->ajaxReturn( $this->result );
//      }
    
        //验证码验证
        if( !check_verify($verify) ){
            $this->ajaxReturnError([
            	'flag'		=> 'code',
            	'msg'		=> L('VERIFY_CHECK_ERROR')
            ]);
        }
        
        //管理员信息
        $admin_map  = [
            'admin_account'     => $account,
            'account_type'      => 1,                  //账号类型；1:平台账号、2：商户主账号、3：商户子账号
            'data_status'       => ['neq', 99],
        ];
        $admin_info = self::$CommonLogic->getRow('AdminInfo', $admin_map);
        
        // 管理员账户验证
        if( !$admin_info ){
            $this->ajaxReturnError([
            	'flag'		=> 'loginname',
            	'msg'		=> L('ADMIN_ACCOUNT_ERROR')
            ]);
        }
        
        //账号状态
        if((int)($admin_info['data_status']) != 1){
            switch((int)$admin_info['data_status']){
                //账号无效；状态异常
                case 2:
                    $this->ajaxReturnError([
		            	'flag'		=> 'loginname',
		            	'msg'		=> L('ADMIN_ACCOUNT_EXCEPT')
		            ]);
                    break;
            }
            // 账号不可用
            $this->ajaxReturnError([
            	'flag'		=> 'loginname',
            	'msg'		=> L('ADMIN_ACCOUNT_DISABLE')
            ]);
        }
        
        //密码验证
        $make_passwd = pass_encode($passwd, $admin_info['admin_salt']);
        if( $admin_info['admin_pass'] !== $make_passwd ){
            $this->ajaxReturnError([
            	'flag'		=> 'password',
            	'msg'		=> L('ADMIN_PWD_ERROR')
            ]);
        }
        
        //管理员登信息
        $login_data['id']                   = $admin_info['id'];
        $login_data['role_id']              = $admin_info['role_id'];
        $login_data['admin_account']        = $admin_info['admin_account'];
        $login_data['admin_name']           = $admin_info['admin_name'];
        
        //存储登陆数据
        self::$CommonLogic->storageLoginData( $login_data );
        
        //记录登陆日志
        $log_info = array(
            'admin_id'  => $admin_info['id'],
            'log_msg'   => $login_data['admin_account'] . L('ADMIN_LOG_LOGIN') . date('Y-m-d H:i:s'),
        );
        self::$CommonLogic->recodeLog($log_info);
        
        //登陆成功
        $this->ajaxReturnSuccess([
    		'flag'	=> 'redirect',
    		'url'	=> 'Index/index'
    	]);
    }
    
    /**
     * 登录检测
     */
    public function loginCheck(){
    	$auth_key = C('AUTH_CONFIG.AUTH_KEY');
        $login_token = session( $auth_key );
        
        // 登录过期
        if( !$login_token ) {
            $this->ajaxReturnError(L('ADMIN_LOGIN_TIMEOUT'));
        }
        
        $this->ajaxReturnSuccess(['result'=>session('login_data.admin_name')]);
    }
    
    /**
     * 注销登录
     */
    public function logout(){
    	// 获取当前管理员信息
    	$admin_info = self::$CommonLogic->getLoginInfo();
    	
        // 没有登录信息时直接跳转到登录页面
        if(!$admin_info){
        	$this->ajaxReturnSuccess([
        		'flag'	=> 'redirect',
        		'url'	=> 'Login/login'
        	]);
        }
        
        //删除登陆数据
        self::$CommonLogic->deleteLoginData();
        
        //记录退出日志
        $log_info = array(
            'admin_id'  => $admin_info['id'],
            'log_msg'   => $admin_info['admin_account'] . ' 注销登陆,时间：' . date('Y-m-d H:i:s'),
        );
        self::$CommonLogic->recodeLog($log_info);
        
        //跳转登陆
        $this->ajaxReturnSuccess([
    		'flag'	=> 'redirect',
    		'url'	=> 'Login/login'
    	]);
    }
    
    /**
     * 请求错误处理
     */
    public function error(){
    	die("Request Error!");
    }
}
